﻿using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using WatchDog;

namespace WatchDogApp.Windows
{
    /// <summary>
    /// LogWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LogWindow
    {
 
    

        //private StringBuilder stringBuilder = new StringBuilder();
        //private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        //{
        //    // 确保窗口句柄已创建
        //    var hwnd = new WindowInteropHelper(this).EnsureHandle();
        //    HwndSource.FromHwnd(hwnd).AddHook(WndProc);
        //}

        //private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        //{
        //    if (msg == WindowsMessageField.WM_COPYDATA)
        //    {
        //        var copyData = Marshal.PtrToStructure<WindowsMessageField.COPYDATASTRUCT>(lParam);
        //        string received = Marshal.PtrToStringAnsi(copyData.lpData);

        //        if (this.IsVisible)
        //        {
        //            this.Dispatcher.Invoke(() =>
        //            {

        //                if (MyRichTextBox.Document.Blocks.Count > 1000)
        //                {
        //                    MyRichTextBox.Document.Blocks.Clear(); // 清空文档的所有内容

        //                }

        //                MyRichTextBox.AppendText(stringBuilder.ToString());
        //                MyRichTextBox.ScrollToEnd();
        //                stringBuilder.Clear();
        //            });
        //        }
                
        //        handled = true;
        //    }
        //    return IntPtr.Zero;
        //}

        

        //public LogWindow()
        //{
        //    InitializeComponent();
        //    //Loaded += MainWindow_Loaded;

        //    //Loaded += async (_, __) => await StartListeningAsync();

        //    this.Activated += (a, b) =>
        //    {
        //        Task.Factory.StartNew(async () => {
        //            while (true)
        //            {
        //                try
        //                {
        //                    using var client = new NamedPipeClientStream(".", "MyAppPipe", PipeDirection.In);
        //                    await client.ConnectAsync();
        //                    using var reader = new StreamReader(client, Encoding.UTF8);
        //                    string message = await reader.ReadToEndAsync();

        //                    Dispatcher.Invoke(() =>
        //                    {
        //                        if (MyRichTextBox.Document.Blocks.Count > 1000)
        //                        {
        //                            MyRichTextBox.Document.Blocks.Clear(); // 清空文档的所有内容

        //                        }

        //                        MyRichTextBox.AppendText(message);
        //                        MyRichTextBox.ScrollToEnd();

        //                    });
        //                }
        //                catch (Exception ex)
        //                {
        //                    await Task.Delay(5000); // 重试间隔
        //                }
        //            }
        //        });
        //    };
        //}

        private CancellationTokenSource _cts;

        public LogWindow()
        {
            InitializeComponent();
            Loaded += OnLoaded;
            Unloaded += OnUnloaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            StartListening();
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            StopListening();
        }

        private void StartListening()
        {
            if (_cts != null) return;

            _cts = new CancellationTokenSource();
            _ = Task.Run(() => ListenLoop(_cts.Token));
        }

        private void StopListening()
        {
            _cts?.Cancel();
            _cts = null;
        }

        private async Task ListenLoop(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    using var client = new NamedPipeClientStream(".", "WatchDogLogToClientPipe", PipeDirection.In);
                    await client.ConnectAsync(token);
                    using var reader = new StreamReader(client, Encoding.UTF8);
                    string message = await reader.ReadLineAsync(token);
                    Dispatcher.Invoke(() => {
                        if (MyRichTextBox.Document.Blocks.Count > 1000)
                        {
                            MyRichTextBox.Document.Blocks.Clear(); // 清空文档的所有内容

                        }

                        MyRichTextBox.AppendText(message + "\n\r");
                        MyRichTextBox.ScrollToEnd();
                    });
                }
                catch (OperationCanceledException)
                {
                    // 正常取消
                }
                catch (IOException ex)
                {
                    //Dispatcher.Invoke(() => txtStatus.Text = "Disconnected: " + ex.Message);
                    await Task.Delay(1000, token); // 重试间隔
                }
            }
        }

    }
}
